﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Plugin.Toasts;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace JWXH.XH.pages.masterdetail
{
    public class SideMenuViewItemSelectdEventArg : EventArgs
    {
        public SideMenuViewItemSelectdEventArg(string text)
        {
            this.Text = text;
        }
        public string Text { get; private set; }
    }

    [XamlCompilation(XamlCompilationOptions.Compile)]
	public partial class SlideMenuView : ContentView
	{
		public SlideMenuView ()
		{
			InitializeComponent ();
//            Device.StartTimer(TimeSpan.FromSeconds(2), () =>
//            {
//                this.IsShowMenu(true);
//                return false;
//            });
//		    this.IsShowMenu(true);
        }

        private double parentHeight = 0;
	    protected override void OnSizeAllocated(double width, double height)
	    {
	        base.OnSizeAllocated(width, height);
	        if (Height > 0)
	        {
	            parentHeight = height;
	        }
	    }
        
	    public static readonly BindableProperty IsPresentedProperty = BindableProperty.Create(
            "IsPresented",
	        typeof(bool),
	        typeof(SlideMenuView),
	        false
	    );

	    public bool IsPresented
        {

	        get => (bool)GetValue(IsPresentedProperty);
	        set
	        {
	            if (value == IsPresented) return;
	            SetValue(IsPresentedProperty, value);

	            IsShowMenu(value);
	        }
	    }

        private void IsShowMenu(bool isShow)
	    {
	        this.MenuMask.IsVisible = isShow;
	        this.MenuContent.IsVisible = isShow;
	        this.IsVisible = isShow;

            if (isShow)
	        {
                var rect = this.MenuContent.Bounds;
	            this.MenuContent.LayoutTo(new Rectangle(0, rect.Y, 200, parentHeight));
	        }
	        else
	        {
                var rect = this.MenuContent.Bounds;
                this.MenuContent.LayoutTo(new Rectangle(0, rect.Y, -200, parentHeight));
            }
	    }

        // 蒙版点击
	    private void MenuMask_OnTapped(object sender, EventArgs e)
	    {
	        this.IsPresented = false;
	    }

	    public event EventHandler<SideMenuViewItemSelectdEventArg> ItemSelectd;

	    protected void OnItemSelected(object sender, System.EventArgs e)
	    {
	        var label = sender as Label;
	        Debug.WriteLine(label.Text);
	        if (ItemSelectd != null)
	        {
	            ItemSelectd(this, new SideMenuViewItemSelectdEventArg(label.Text));
	        }
	    }
    }
}